//
//  WBMainViewController.swift
//  weibo
//
//  Created by swift on 17/2/22.
//  Copyright © 2017年 jason. All rights reserved.
//

import UIKit
//主控制器
class WBMainViewController: UITabBarController {
    //定时器
    fileprivate var timer:Timer?

    override func viewDidLoad() {
        super.viewDidLoad()
       //1.设置各子控制器
        setupChildControllers()
        //2.设置撰写按钮
        setupComposeButton()
      //3.设置settimer
         settimer()
        //设置代理
        delegate = self
        
    }
    //销毁时钟
    deinit{
        timer?.invalidate()
    }
    //.portrait竖屏
    //.landscapeLeft横屏
    //使用代码控制设备的方向,好处可以在需要横屏的时候,单独处理,设置支持的方向之后,当前的控制器以及子控制器都会遵守这个方向,如果播放视频,通常是通过modal展现的
    //MARK:-设置设备的方向支持
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
         return [UIInterfaceOrientationMask.portrait]
    }
    
    //MARK:-中间按钮监听方法
    //private能保证私有,仅在当前对象被访问
    //@objc 允许这个函数在"运行时"通过oc的消息机器被调用
    @objc fileprivate func composseStatus(){
        print ("///")
        //测试方向的旋转
        let vc = UIViewController()
        vc.view.backgroundColor = UIColor.cz_random()
        let nav = UINavigationController(rootViewController: vc)
        present(nav, animated: true, completion: nil)
    }
    ///撰写微博
    //MARK:-私有控件
    //撰写按钮(中间)
    fileprivate lazy var composeButton:UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
   
}
//实现tabbarcontrol的代理
extension WBMainViewController:UITabBarControllerDelegate{
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
       // print("将要切换到\(viewController)")
        //获取控制器在数组中的索引
        let index = (childViewControllers as NSArray).index(of: viewController)
        //判断当前索引是否是首页
        
/*测试用
        print("---------------------")
        let nvi1 = childViewControllers[0]
        let nvi2 = childViewControllers[0] as! UINavigationController
        let vc = nvi2.childViewControllers
        let vc2 = nvi2.childViewControllers[0]
        let vc3 = nvi2.childViewControllers[0] as! WBHomeViewController
        print(childViewControllers)
        print(nvi1)
        print(nvi2)
        print("---------------------")
        print(vc)
        print(vc2)
        print(vc3)
        print("---------------------")
*/
        
        
        if selectedIndex == 0 && index == selectedIndex {
         //  print("点击首页")
        //让表格滚到到顶部
            let nav = childViewControllers[0] as! UINavigationController
            
            let vc = nav.childViewControllers[0] as! WBHomeViewController
            vc.tableView?.setContentOffset(CGPoint(x:0,y:-64), animated: true)
        //刷新数据(延时一秒)
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: { 
                vc.loaddata()
            self.tabBar.items?[0].badgeValue = nil
            })
        }
        return true
    }
    
}
//时钟
extension WBMainViewController{
    fileprivate func settimer(){
        timer = Timer.scheduledTimer(timeInterval: 60, target: self, selector:#selector(updatetime) , userInfo: nil, repeats: true)
    }
    @objc private func  updatetime(){
        weibonetwork.shared.unreadcount { (count) in
            print("监测到\(count)数据")
            //设置首页tabbaritem的bagenumber
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)":nil
            //设置app的bagenumber(ios8.0以后需要用户授权)
            UIApplication.shared.applicationIconBadgeNumber = count
            
        }
    }
}
//切分代码块,可以把相同相近的函数放在extension中,便于代码维护
//MARK:-设置界面
extension WBMainViewController{
    ///设置撰写按钮
    fileprivate func setupComposeButton(){
    tabBar.addSubview(composeButton)
    //计算撰写按钮的宽度
    let count = CGFloat(childViewControllers.count)
    //将向内缩进的宽度减小,能够让按钮的宽度变大,盖住容错点,防止穿帮
    let w = tabBar.bounds.width/count - 1
     //insetBy 正数向内缩进,负数向外缩进
    composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
    //按钮的监听方法
        composeButton.addTarget(self, action: #selector(composseStatus), for: .touchUpInside)
    }
    //设置所有子控制器
    fileprivate func setupChildControllers(){
        //获取沙盒的json路径
        let docdir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonpath = (docdir as NSString).appendingPathComponent("url.json")
        //从json中加载数据(从沙盒中找到json,并加载data)
        var data = NSData.init(contentsOfFile: jsonpath)
        if data == nil{
            //从bundle中获取文件,并加载数据
            let path = Bundle.main.path(forResource: "demo.json", ofType: nil)
            data = NSData.init(contentsOfFile: path!)
            
        }
        //从bundle加载配置的json
        //1路径2加载nsdata(从bundle中加载)3反序列化转换线数组
        guard /*let path = Bundle.main.path(forResource: "demo.json", ofType: nil),let data = NSData.init(contentsOfFile: path),*/let arry = try! JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String:Any]] else {
            return
        }
//        let arry:[[String:Any]] = [["clsName":"WBHomeViewController","title":"首页","imageName":"home","visitorinfo":["imagename":"","message":"关注一些人...登录后,别人评论你的微博登录后,别人评论你的微博"] ]
//            ,["clsName":"WBMessageViewController","title":"消息","imageName":"message_center","visitorinfo":["imagename":"visitordiscover_image_message","message":"登录后,别人评论你的微博登录后,别人评论你的微博登录后,别人评论你的微博"]]
//            ,["clsName":"空视图,为了添加按钮"]
//            ,["clsName":"WBDiscoverViewController","title":"发现","imageName":"discover","visitorinfo":["imagename":"visitordiscover_image_message","message":"最新,最热的微博尽在掌握登录后,别人评论你的微博登录后,别人评论你的微博"]],["clsName":"WBProfileViewController","title":"我","imageName":"profile","visitorinfo":["imagename":"visitordiscover_image_profile","message":"微博,相册,个人资料登录后,别人评论你的微博登录后,别人评论你的微博"]]]
//            //(arry as NSArray).write(toFile:"/Users/jason/Desktop/demo.plist", atomically: true)
//        let data = try! JSONSerialization.data(withJSONObject: arry, options: [.prettyPrinted])
//        (data as NSData).write(toFile:"/Users/jason/Desktop/demo.json", atomically: true)
        //遍历数组,循环创建控制器数组
        var arryM = [UIViewController]()
        for dict in arry{
            arryM.append(controller(dict: dict))
            
        }
        //设置tabbar的子控制器
        viewControllers = arryM
    }
     ///使用字典创建一个子控制器
    //dict:信息字典(子视图控制器的名字clsname,title,imagename,visitorinfo)
    private func controller(dict:[String:Any])->UIViewController{
        //1.取得字典的内容
        guard let clsName = dict["clsName"] as? String,let title = dict["title"] as? String,let imageName = dict["imageName"] as? String,let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type ,let visitorinfo = dict["visitorinfo"] as? [String:String] else {
            return UIViewController()
        }
        
        //2.创建视图控制器
        let vc = cls.init()
        // 设置TabBar和Nav的标题
        vc.title = title
        //设置控制视图的访客信息
        vc.visitorinfodict = visitorinfo
        //设置tabbar 的图像
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        //设置tabbar标题字体,颜色(NSForegroundColorAttributeName前景色,NSFontAttributeName字体大小)
        //字典
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .highlighted)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 13)], for: .normal)
        
        // 包装导航控制器
        let nav = WBNavigationController(rootViewController: vc)
        return nav
       
    }
}
